package com.rabbiter.market.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成器
 */
public class QRUtil {

    //CODE_WIDTH：二维码宽度，单位像素
    private static final int CODE_WIDTH = 400;

    //CODE_HEIGHT：二维码高度，单位像素
    private static final int CODE_HEIGHT = 400;

    //FRONT_COLOR：二维码前景色，0x000000 表示黑色
    private static final int FRONT_COLOR = 0x000000;

    //BACKGROUND_COLOR：二维码背景色，0xFFFFFF 表示白色
    //演示用 16 进制表示，和前端页面 CSS 的取色是一样的，注意前后景颜色应该对比明显，如常见的黑白
    private static final int BACKGROUND_COLOR = 0xFFFFFF;

    // logo图片
    private static final String ALIPAY_LOGO_IMAGE = "static/img/alipay-logo.jpg";

    public static void createCodeToOutputStream(String content, OutputStream outputStream) {
        if(content.isEmpty()) {
            return;
        }
        try {
            BufferedImage qrCodeImage = drawLogo(getBufferedImage(content));
            //区别就是这一句，输出到输出流中，如果第三个参数是 File，则输出到文件中
            ImageIO.write(qrCodeImage, "png", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //核心代码-生成二维码
    private static BufferedImage getBufferedImage(String content) throws WriterException {

        //com.google.zxing.EncodeHintType：编码提示类型,枚举类型
        Map<EncodeHintType, Object> hints = new HashMap<>();

        //EncodeHintType.CHARACTER_SET：设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        /*
        * EncodeHintType.ERROR_CORRECTION：设置误差校正
        * ErrorCorrectionLevel：误差校正等级，L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
        * 不设置时，默认为 L 等级，等级不一样，生成的图案不同，但扫描的结果是一样的
        */
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        /* EncodeHintType.MARGIN：设置二维码边距，单位像素，值越小，二维码距离四周越近 */
        hints.put(EncodeHintType.MARGIN, 1);

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
        BufferedImage qrCodeImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
        for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                qrCodeImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }

        return qrCodeImage;
    }

    // 为二维码添加logo
    public static BufferedImage drawLogo(BufferedImage qrCodeImage) throws IOException {
        int width = qrCodeImage.getWidth();
        int height = qrCodeImage.getHeight();

        // 构建绘图对象
        Graphics2D g = qrCodeImage.createGraphics();
        // 读取Logo图片
        ClassPathResource resource = new ClassPathResource(ALIPAY_LOGO_IMAGE);
        InputStream inputStream = resource.getInputStream();
        BufferedImage logo = ImageIO.read(inputStream);
        // 开始绘制logo图片
        g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
        g.dispose();
        logo.flush();

        return qrCodeImage;
    }

}
